package com.ityuwen.mengyagushi.live.service.impl;

import com.ityuwen.mengyagushi.common.util.AuthContextHolder;
import com.ityuwen.mengyagushi.live.mapper.LiveRoomMapper;
import com.ityuwen.mengyagushi.live.service.LiveRoomService;
import com.ityuwen.mengyagushi.live.utils.LiveAddressUtil;
import com.ityuwen.mengyagushi.model.live.LiveRoom;
import com.ityuwen.mengyagushi.vo.live.LiveRoomVo;
import com.ityuwen.mengyagushi.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Autowired
	private LiveAddressUtil liveAddressUtil;

	@Override
	public LiveRoom getCurrentLive() {
		return this.liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>()
				.eq(LiveRoom::getUserId, AuthContextHolder.getUserId())
				.gt(LiveRoom::getExpireTime, new Date()));
	}

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo roomVo) {
		// 检验是否存在未过期的直播间
		LiveRoom liveRoom = this.liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>()
				.eq(LiveRoom::getUserId, AuthContextHolder.getUserId())
				.gt(LiveRoom::getExpireTime, new Date()));
		if (liveRoom != null){
			return liveRoom;
		}

		// 如果不存在未过期的直播间则新增
		liveRoom = new LiveRoom();
		BeanUtils.copyProperties(roomVo, liveRoom);
		liveRoom.setUserId(AuthContextHolder.getUserId());
		liveRoom.setStatus("1");
		liveRoom.setAppName("谷粒随享直播功能");
		// 主播使用我们的直播应用  在腾讯云中的streamName
		String streamName = "ityuwen" + IdWorker.getIdStr();
		liveRoom.setStreamName(streamName);
		Date expireTime = liveRoom.getExpireTime(); // 直播过期时间
		// 获取推拉流地址
		TencentLiveAddressVo tencentLiveAddresses = liveAddressUtil.getTencentLiveAddresses(expireTime.getTime() / 1000, streamName);
		liveRoom.setPushUrl(tencentLiveAddresses.getPushWebRtcUrl());
		liveRoom.setPlayUrl(tencentLiveAddresses.getPullWebRtcUrl());
		this.save(liveRoom);

		return liveRoom;
	}
}
